const express = require('express');
const routerUser = require('./router/user')
const cors = require('cors');
const { expressjwt: expressJWT } = require('express-jwt');
const { jwtSereKey } = require('./config');
const joi = require('joi')
const updateUserRouter = require('./router/updateUser')
const listRouter = require('./router/list')
const app = express();
app.use(cors())
app.use(express.urlencoded({extended:false}))
app.use(express.json())

app.use((req,res,next)=> {
    res.cc = (err,status=1)=> {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

app.use(
    expressJWT({ 
      secret: jwtSereKey, 
      algorithms: ['HS256'],
      credentialsRequired: true // 明确指定需要令牌
    }).unless({ 
      path: [/^\/api\//] 
    })
  )





app.use('/api',routerUser)
app.use('/my',updateUserRouter)
app.use('/list',listRouter)




app.use((err,req,res,next)=> {
    if(err instanceof joi.ValidationError) {
        return res.cc(err)
    }
    if(err.name === 'UnauthorizedError') {
        return res.cc('身份认证失败') 
    }
    res.cc(err)
})

app.listen(8080, () => {
  console.log('Server is running on port http://localhost:8080');
});

